package com.yu1996.stack;

import java.util.Scanner;

public class ArrayStackDemo {

    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
//        stack.list();
        String key = "";
        boolean flag = true;
        Scanner scanner = new Scanner(System.in);
        while (flag) {
            System.out.println("1.show：表示显示栈   2.pop：表示出栈  3.push：表示入栈   4.exit：表示退出");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.list();
                    break;
                case "pop":
                    int pop = stack.pop();
                    System.out.printf("出栈的是：%d\n", pop);
                    break;
                case "push":
                    System.out.println("请输入入栈的数：");
                    int i = scanner.nextInt();
                    stack.push(i);
                    break;
                case "exit":
                    System.out.println("程序结束，再见~~~~~");
                    flag = false;
                    break;
                default:
                    System.out.println("输入不合法");
                    break;
            }

        }
    }
}

class ArrayStack {
    private int maxSize;
    private int[] arr;
    private int top = -1;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        //初始化数组
        arr = new int[maxSize];
    }


    /**
     * @Description 判断栈是否已满
     * @Author xing
     * @Date 2019/8/4 11:29
     * @Param
     * @Return
     * @Exception
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }


    /**
     * @Description 判断栈是否为空
     * @Author xing
     * @Date 2019/8/4 11:29
     * @Param
     * @Return
     * @Exception
     */
    public boolean isEmpty() {
        return top == -1;
    }


    /**
     * @Description 入栈
     * @Author xing
     * @Date 2019/8/4 11:30
     * @Param
     * @Return
     * @Exception
     */
    public void push(int val) {
        //判断是否栈满
        if (isFull()) {
            System.out.println("栈满，无法入栈");
            return;
        }
        top++;
        arr[top] = val;
    }


    /**
     * @Description 出栈
     * @Author xing
     * @Date 2019/8/4 11:32
     * @Param
     * @Return
     * @Exception
     */
    public int pop() {
        //判断是否栈空
        if (isEmpty()) {
            throw new RuntimeException("栈空，无法出栈");
        }
        int val = arr[top];
        top--;
        return val;
    }

    public void list() {
        //判断是否为空
        if (isEmpty()) {
            System.out.println("栈空，无法输出");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("arr[%d]=%d\n", i, arr[i]);
        }
    }
}